package cn.tedu.imop.attach.controller;

import cn.tedu.imop.api.domain.Attach;
import cn.tedu.imop.api.model.RestResult;
import cn.tedu.imop.api.model.RestResultUtils;
import cn.tedu.imop.attach.service.AttachService;
import cn.tedu.imop.attach.utils.FileUtils;
import cn.tedu.imop.common.constants.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "附件上传")
/**
 * 文件请求处理
 */
@RestController
@RequestMapping(value=Constants.CONTROLLER_API_VERSION+"/attach")
public class AttachController
{
    private static final Logger log = LoggerFactory.getLogger(AttachController.class);

    @Value("${server.port}")
    private Integer port;
    @Autowired
    private AttachService attachService;

    /**
     * 文件上传请求
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public RestResult<Attach> upload(MultipartFile file) {
        log.info("{} 服务正在处理资源上传",port);
        try {
            // 上传并返回访问地址
            String url = attachService.uploadAttach(file);
            Attach attach = new Attach();
            attach.setUuidFileName(FileUtils.getName(url));
            attach.setStoragePath(url);
            attachService.createAttach(attach);
            return RestResultUtils.success(attach);
        }
        catch (Exception e) {
            log.error("上传文件失败", e);
            return RestResultUtils.failed(e.getMessage());
        }
    }
    @PutMapping("/binding")
    public RestResult<Void> batchBindingAttach(@RequestBody ArrayList<Attach> params)
    {
        System.out.println("---------超时重试中ing------------" + LocalDateTime.now());
        try {
            Thread.sleep(5000);
        }catch (Exception e){}
        log.debug("imop-attach-{}:绑定图片信息: {}",port,params);
        //基于附件id跟新附件表数据，做附件和商家信息的绑定。(更新表的信息不写了)
        return RestResultUtils.success();
    }


}